<?php

namespace App\Dao;

use App\Model\Closeness;
use App\Model\User;
use App\Services\PushMessageService;
use function Hyperf\Translation\trans;

class ClosenessDao
{

    /**
     * 记录用户亲密度
     * @param $uid int|string 用户id
     * @param $anchor_id int|string 主播id
     * @param $score int|string 消耗金币
     * @param $send_upgrade bool 是否发送升级消息
     */
    public static function write($uid, $anchor_id, $score, $send_upgrade = true)
    {
        $time = time();
        $old_score = self::read($uid, $anchor_id);
        $score = (int)$score;
        $score = $old_score + $score;
        $res = Closeness::query()->updateOrInsert([
            'uid' => $uid,
            'anchor_id' => $anchor_id
        ], ['score' => $score, 'update_time' => $time]);

        // 亲密度升级发送im消息
        if ($res && $send_upgrade) {
            self::sendClosenessUpgradeMsg($uid, $anchor_id, $score, $old_score);
        }
        return $res;

    }


    /**
     * 获取用户关系亲密度
     * @param $uid
     * @param $anchor_id
     * @return int
     */
    public static function read($uid, $anchor_id)
    {
        // $result = (new self())->find("*","uid=? and anchor_id=?",[$uid,$anchor_id]);
        $result = Closeness::query()->where(['uid' => $uid, 'anchor_id' => $anchor_id])->first();
        if (empty($result)) {
            return 0;
        }
        return (int)$result['score'];
    }


    /**
     * 获取关系亲密度等级,并匹配关系亲密度等级
     * @param $closeness
     * @return int
     */
    public static function getClosenessLevel($closeness)
    {
        $closeness_param = CommonSettingDao::getInstance()->getList("CLOSENESS_PARAM");

        $param = json_decode($closeness_param['value'], true);

        $level = 0;
        foreach ($param as $item) {
            if ($item['score'] <= $closeness) {
                $level = $item['level'];
            }
        }
        return (int)$level;
    }


    /**
     * Note - 批量获取用户关系亲密度
     * DateTime 2024/7/19 12:40
     * User Admin
     * @param $uid
     * @param $sex
     * @param $uids
     * @return array
     */
    public static function getMyCloseness($uid, $sex, $uids)
    {
        if (empty($uids)) {
            return [];
        }
        if (!is_array($uids)) {
            $uids = explode(",", $uids);
        }
        if ($sex == 1) {
            // $where = "uid=? and anchor_id in ($uids)";
            $result = Closeness::query()->where('uid', $uid)->whereIn('anchor_id', $uids)->get()->toArray();
        } else {
            // $where = "anchor_id=? and uid in ($uids)";
            $result = Closeness::query()->where('anchor_id', $uid)->whereIn('uid', $uids)->get()->toArray();
        }

        if (empty($result)) {
            return [];
        } else {
            if ($sex == 1) {
                return array_column($result, 'score', 'anchor_id');
            } else {
                return array_column($result, 'score', 'uid');
            }
        }
    }


    /**
     * 是否发送升级提示
     * @param $uid
     * @param $anchor_id
     * @param $score
     * @param $old_score
     * @return void
     */
    public static function sendClosenessUpgradeMsg($uid, $anchor_id, $score, $old_score)
    {
        $users = User::query()
            ->select(['id', 'nickname', 'head_image', 'register_time', 'ext2'])
            ->whereIn('id', [$uid, $anchor_id])
            ->get()
            ->keyBy('id')
            ->toArray();
        $old_level = self::getClosenessLevel($old_score);
        $new_level = self::getClosenessLevel($old_score + $score);
        // 亲密度升级通知
        if ($new_level > $old_level) {
            $ctime = getMillisecond();
            // Function to create notification message
            $createNotification = function ($uid, $receive_uid) use ($users, $new_level, $ctime) {
                $uExt2Array = $users[$receive_uid]['ext2'];
                $language = $uExt2Array['language'] ?? 'en';
                $upgrade_data = ['level' => $new_level, 'power' => '', 'power_desc' => '', 'next_power' => ''];
                switch ($new_level) {
                    case 1:
                        $upgrade_data['power'] = trans("message.音视频通话", [], $language);
                        $upgrade_data['power_desc'] = trans("message.看看TA动人的脸庞", [], $language);
                        $upgrade_data['next_power'] = trans("message.达到Lv.2即可解锁语音消息权限", [], $language);
                        break;
                    case 2:
                        $upgrade_data['power'] = trans("message.语音消息", [], $language);
                        $upgrade_data['power_desc'] = trans("message.解锁语音消息权限", [], $language);
                        $upgrade_data['next_power'] = trans("message.达到Lv.3即可解锁发送图片消息权限", [], $language);
                        break;
                    case 3:
                        $upgrade_data['power'] = trans("message.图片消息", [], $language);
                        $upgrade_data['power_desc'] = trans("message.解锁图片消息权限", [], $language);
                        break;
                    default:
                        break;
                }
                $content_type = 1;
                $chat_type = 30;
                $msgContent = trans("message.恭喜你亲密度等级升级", ['level' => $new_level, 'nickname' => $users[$uid]['nickname']], $language);
                $is_new_user = ($users[$uid]['register_time'] + 7 * 86400 >= time()) ? 1 : 0;
                $notification = [
                    'uid' => (int)$uid,
                    'receive_uid' => (int)$receive_uid,
                    'content' => $msgContent,
                    'ctime' => $ctime,
                    'chat_type' => $chat_type,
                    'content_type' => $content_type,
                    'upgrade_data' => $upgrade_data,
                    'user_info' => $users[$uid],
                    'receiver' => $users[$receive_uid],
                    'is_new_user' => $is_new_user,
                ];
                return json_encode(['event' => 'closeness_upgrade', 'msg' => $notification]);
            };

            PushMessageService::putYunXinSendAttachMsgQueue($uid, $anchor_id, $createNotification($uid, $anchor_id));
            PushMessageService::putYunXinSendAttachMsgQueue($anchor_id, $uid, $createNotification($anchor_id, $uid));
        }

    }


}